package org.hidaron.example.demo.download.adapter;

import java.util.List;

import org.hidaron.asyncdownloader.R;
import org.hidaron.asyncdownloader.download.Downloader;
import org.hidaron.asyncdownloader.utils.NetWorkUtils;
import org.hidaron.asyncdownloader.utils.ToastUtils;
import org.hidaron.example.demo.download.AppInfo;
import org.hidaron.example.demo.download.service.DownloadService.DownloadBinder;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class DownloadListAdapter extends DefaultAdapter<AppInfo> {
	private static final String TAG = DownloadListAdapter.class.getSimpleName();
	private Context mContext;
	private DownloadBinder mBinder;

	public static class ViewHolder {
		public TextView appName;
		public TextView speed;
		public ProgressBar pargressBar;
		public Button button;
	}

	public DownloadListAdapter(Context context, List<AppInfo> testInfo,
			DownloadBinder binder) {
		super(testInfo);
		mContext = context;
		mBinder = binder;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final AppInfo info = getItem(position);
		final ViewHolder holder;
		View view = convertView;
		if (null == view) {
			view = LayoutInflater.from(mContext).inflate(
					R.layout.view_download_list_item, null);
			holder = new ViewHolder();
			holder.appName = (TextView) view
					.findViewById(R.id.download_app_name);
			holder.speed = (TextView) view.findViewById(R.id.download_speed);
			holder.pargressBar = (ProgressBar) view
					.findViewById(R.id.download_progressbar);
			holder.button = (Button) view.findViewById(R.id.download_button);
			view.setTag(holder);
		} else {
			holder = (ViewHolder) view.getTag();
		}
		holder.appName.setText(info.getAppName());
		holder.button.setText(R.string.start);
		holder.button.setOnClickListener(new OnClickListener() {
			private Downloader downloader;

			@Override
			public void onClick(View view) {
				if (view == holder.button) {
					if (null == mBinder) {
						return;
					}
					if (!NetWorkUtils.isCurrentNetWorkConnected(mContext)) {
						ToastUtils.warning((Activity) mContext,
								R.string.network_not_connectable);
						return;
					}
					if (holder.button.getText().equals("取消")) {
						mBinder.cancelDownload(downloader);
					} else if (holder.button.getText().equals("继续下载")) {
						Log.d(TAG, "continue start");
						mBinder.continueDownload(downloader);
					} else if (holder.button.getText().equals("下载")
							|| holder.button.getText().equals("重新下载")) {
						holder.button.setText("等待");
						downloader = mBinder.startDownload(mContext, info,
								holder);
					}
				}
			}
		});
		return view;
	}
}
